#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: buffer.py
# Description: 
#   buffer(object[, offset[, size]])¶
#   The object argument must be an object that supports the buffer call interface 
#   (such as strings, arrays, and buffers). A new buffer object will be created 
#   which references the object argument.
#
#   Note that buffer has been replaced by the better named memoryview in Python 3,
#   though you can use either in Python 2.7.
# Edit History: 
#   2011-10-13    File created.
#===============================================================================

# The buffer in this case is a sub-string, starting at position 6 with length 5,
# and it doesn't take extra storage space - it references a slice of the string.
s = 'Hello world'
b = buffer(s, 6, 5)
c = buffer(s, 6, 5)
print(b) # world
print(type(b))
print(id(b))
print(b.__repr__())
print(id(c))
print(c.__repr__())
print(id(s))
print(c.__repr__())

# This isn't very useful for short strings like this, but it can be necessary 
# when using large amounts of data. This example uses a mutable bytearray
s = bytearray(1000000)   # a million zeroed bytes
t = buffer(s, 1)         # slice cuts off the first byte
s[1] = b'a'                 # set the second element in s
s[2] = 98                 # set the third element in s
print(t[0])  # a
print(t[1])  # b

# In general a slice will take extra storage, so yes s[6:11] will be a copy. 
# If you set t = s[6:11] and then del s, it frees the memory that was taken by s,
# proving that t was copied.
